<script setup lang="ts">
import { ref, reactive, onMounted, defineEmits } from "vue";
import type { FormRules } from "element-plus";
import { getOrgList, addOrg, addOrgDto } from "@/api/sys/org";

const emit = defineEmits(["onSearchEnv"]);
const onSearchTable = () => {
  emit("onSearchEnv");
};
const deptForm = ref<addOrgDto>({
  parentId: "",
  orgName: "",
  status: 1
});
onMounted(() => {});

const showdialogForAddDept = () => {
  deptForm.value = {
    parentId: "",
    orgName: "",
    status: 1
  };
  getOrgList().then(res => {
    const li = [];
    res.forEach(item => {
      li.push({
        label: item.orgName,
        value: item.id
      });
      deptList.value = li;
    });
  });
  dialogVisible.value = true;
};

const dialogVisible = ref(false);
const deptList = ref<any>([]);

const statusOptions = [
  {
    label: "正常",
    value: 1
  },
  {
    label: "冻结",
    value: 2
  }
];
const rules = reactive<FormRules>({
  orgName: [
    {
      required: true,
      message: "请输入部门名称",
      trigger: "blur"
    }
  ],
  parentId: [
    {
      required: true,
      message: "请选择上级部门",
      trigger: "change"
    }
  ],
  status: [
    {
      required: true,
      message: "状态不能为空",
      trigger: "change"
    }
  ]
});

const onSubmit = () => {
  addOrg(deptForm.value).then(() => {
    dialogVisible.value = false;
    onSearchTable();
  });
};

defineExpose({
  showdialogForAddDept
});
</script>

<template>
  <el-dialog v-model="dialogVisible" title="添加部门">
    <el-form ref="elForm" :model="deptForm" :rules="rules" label-width="100px">
      <el-form-item label="部门名称" prop="orgName">
        <el-input
          v-model="deptForm.orgName"
          placeholder="请输入部门名称"
          :maxlength="20"
          show-word-limit
          clearable
        />
      </el-form-item>
      <el-form-item label="部门状态" prop="status">
        <el-radio-group v-model="deptForm.status">
          <el-radio
            v-for="(item, index) in statusOptions"
            :key="index"
            :label="item.value"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>

      <el-form-item label="上级部门" prop="parentId">
        <el-select
          v-model="deptForm.parentId"
          placeholder="请选择上级部门"
          clearable
          :style="{ width: '100%' }"
        >
          <el-option
            v-for="(item, index) in deptList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped></style>
